package controller;

import remoteEntity.Filedescription;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import manager.FileManager;
import manager.LogManager;

/**
 * FileInfoController
 *
 * JSF Managed backing bean containing model showing logic for the indivisual
 * file info page. Also has logic for removing filesdescriptions for
 * administrators.
 */
@ManagedBean
@ViewScoped
public class FileInfoController implements Serializable {

    @EJB
    private FileManager fileManager;
    @EJB
    private LogManager logManager;
    private Filedescription fd = null;
    private Integer fileId;
    @ManagedProperty(value = "#{userController}")
    private UserController userController;

    public UserController getUserController() {
        return userController;
    }

    public void setUserController(UserController userController) {
        this.userController = userController;
    }

    @PostConstruct
    public void init() {
        this.fileId = Integer.valueOf(FacesContext.getCurrentInstance().
                getExternalContext().getRequestParameterMap().get("id"));
    }

    public void deleteFile() {
        if (userController.getIsAdmin()) {
            fileManager.deleteFile(fileId);
            logManager.logInfo("fileinfo", "User " + userController.getUser().getUsername()
                    + " (id " + userController.getUser().getId() + ") deleted file id " + fileId + ".");
        } else {
            logManager.logWarning("fileinfo", "User " + userController.getUser().getUsername()
                    + " (id " + userController.getUser().getId() + ") tried to delete file id " + fileId + " but does not have authority.");
        }
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("browse");
        } catch (Exception e) {
        }
    }

    public Filedescription getFileinfo() {
        return fileManager.getFile(this.fileId);
    }
}
